"""
Utility functions for the tank battle game
"""
import math
import pygame
from .config import WINDOW_WIDTH, WINDOW_HEIGHT

def clamp(value, min_value, max_value):
    """Clamp a value between min and max"""
    return max(min_value, min(value, max_value))

def distance(point1, point2):
    """Calculate distance between two points"""
    return math.sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2)

def normalize_vector(vector):
    """Normalize a 2D vector"""
    length = math.sqrt(vector[0]**2 + vector[1]**2)
    if length == 0:
        return (0, 0)
    return (vector[0] / length, vector[1] / length)

def is_point_in_rect(point, rect):
    """Check if a point is inside a rectangle"""
    return (rect.left <= point[0] <= rect.right and 
            rect.top <= point[1] <= rect.bottom)

def is_point_in_window(point):
    """Check if a point is within the game window"""
    return (0 <= point[0] <= WINDOW_WIDTH and 
            0 <= point[1] <= WINDOW_HEIGHT)

def load_image(path, scale=None):
    """Load and optionally scale an image"""
    try:
        image = pygame.image.load(path)
        if scale:
            image = pygame.transform.scale(image, scale)
        return image
    except pygame.error as e:
        print(f"Error loading image {path}: {e}")
        return None

def load_sound(path):
    """Load a sound file"""
    try:
        return pygame.mixer.Sound(path)
    except pygame.error as e:
        print(f"Error loading sound {path}: {e}")
        return None

def create_text_surface(text, font, color=(255, 255, 255)):
    """Create a text surface with given font and color"""
    return font.render(text, True, color)
